package com.cykj.page05;

import com.cykj.page05.servlet.BaseServlet;
import com.cykj.page05.util.ServletUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.sql.SQLOutput;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page05
 * @Author: 阿隆
 * @CreateTime: 2025-10-18 16:19
 * @Description: TODO
 * @Version: 1.0
 */
public class ThreeServeToDynamicServlet {
    public static void main(String[] args) {
        try {
            //创建ServerSocket => 服务器
            ServerSocket serverSocket = new ServerSocket(9090);

            System.out.println("服务端启动端口号为: 9090");

            while (true) {

                //等待客户端连接  阻塞
                Socket socket = serverSocket.accept();

                //读取客户端发送的消息
                InputStream is = socket.getInputStream();

                byte[] bytes = new byte[1024 * 8];

                //读取
                int len = is.read(bytes);

                //请求消息
                String request = new String(bytes, 0, len);

                String decode = URLDecoder.decode(request, "UTF-8");

                System.out.println(decode);


                //解析消息
                MyHttpRequest httpRequest = new MyHttpRequest(request);

                //响应数据
                MyHttpResponse httpResponse = new MyHttpResponse(socket);


                String servletName = ServletUtils.getServletNameToKey(httpRequest.getRequestModel());

                //拼接全路径
                String servletPath = "com.cykj.page05.servlet." + servletName;

                //如果没有获取到serlet的类名  有可能是静态资源
                if (servletName == null) {
                    servletPath = "com.cykj.page05.servlet.DefaultServlet";
                }


                try {
                    //获取类对象
                    Class<?> cls = Class.forName(servletPath);

                    //创建类对象实例
                    BaseServlet baseServlet = (BaseServlet) cls.newInstance();

                    //调用方法
                    baseServlet.requestMethodHandler(httpRequest, httpResponse);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }


            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
